package com.mjk.common.web.getway.restful.interceptor.type.commons.impl;


import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.tools.interceptor.InterceptorChain;
import com.mjk.common.util.MapUtils;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.web.getway.constns.GetWayError;
import com.mjk.common.web.getway.constns.GetwayConsts;
import com.mjk.common.web.getway.restful.interceptor.GetWayInterceptorReq;
import com.mjk.common.web.getway.restful.interceptor.annotation.BeeGetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptor;
import com.mjk.common.web.getway.restful.interceptor.type.GetWayInterceptorType;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;

/**
 * 网关参数效应
 * @author mjk
 *
 */
@BeeGetWayInterceptor(value=2,interceptorType={GetWayInterceptorType.COMMON,GetWayInterceptorType.EXPORT})
public class GetWayParamsCheckInterceptor implements GetWayInterceptor {
	@Value("${bee.must.param.version:dict}")
	private String MUST_PARAMS_VERSION;//必带参数效应版本号
	@Value("${bee.must.carry.param:#{null}}")
	private String MUST_PARAMS_NAMES;//效应的必带参数名称
	//定义不进行 必带参数 效应的URL
	private final String[] notCheckUrl = new String[]{"/ld/common/v1/inpatorder"};
	@Override
	public BeeResponse interceptor(GetWayInterceptorReq request,
								   InterceptorChain<GetWayInterceptorReq, BeeResponse> next) {
		Map<String,Object> paramsMaps = request.getParams();
		String url = request.getRequest().getRequestURI();
		boolean isCheck = true;
		for(String checkUrl : notCheckUrl){
            if (null != url && url.equals(checkUrl)) {
                isCheck = false;
                break;
            }
		}		
		if(!MapUtils.getString(request.getRestfulParams(), GetwayConsts.VERSION).toLowerCase().equals(MUST_PARAMS_VERSION)&&isCheck){
			if(com.mjk.common.util.ObjectUtils.isNotEmpty(MUST_PARAMS_NAMES)){
				String[] names = MUST_PARAMS_NAMES.split(",");
				for(String name : names){
					if(!paramsMaps.containsKey(name)|| ObjectUtils.isEmpty(paramsMaps.get(name))){
						return GetWayError.MUST_PARAMS_IS_NULL.tranceError("");
					}
				}
			}
		}
		return next.proceed(request);
	}
}
